<template>
  <div class="container">
    <div class="main">
      <!-- 表格头部操作区域 -->
      <div class="header">
        <el-button type="primary" @click="add">新建</el-button>
        <el-button type="success" @click="importData">导入</el-button>
        <el-button type="warning" @click="edit">编辑</el-button>
        <el-select v-model="selectedFilter" placeholder="请选择状态" style="width: 200px;">
          <el-option label="启用" value="enabled"></el-option>
          <el-option label="禁用" value="disabled"></el-option>
        </el-select>
        <el-input placeholder="请输入关键字搜索" v-model="searchTable" style="width: 200px;" />
        <el-button type="info" @click="query">查询</el-button>
        <el-button type="info" @click="reset">重置</el-button>
      </div>
      <!-- 表格展示数据 -->
      <el-table :data="filteredTableData" border class="eltable">
        <el-table-column type="index"  label="序号" width="80"></el-table-column>
        <el-table-column prop="gy_code" label="工艺路线编码" width="120"></el-table-column>
        <el-table-column prop="gy_name" label="工艺路线名称" width="150"></el-table-column>
        <el-table-column label="工艺路线分类">
          <template #default="{ row }">
            {{ getDictionaryName(row.gy_fl) }}
          </template>
        </el-table-column>
        <el-table-column prop="gy_bb" label="工艺路线版本"></el-table-column>
        <el-table-column prop="cp_code" label="产品编码" width="150"></el-table-column>
        <el-table-column prop="cp_name" label="产品名称"></el-table-column>
        <el-table-column label="产品分类">
          <template #default="{ row }">
            {{ getDictionaryName(row.cp_fl) }}
          </template>
        </el-table-column>
        <el-table-column prop="cp_xh" label="产品型号"></el-table-column>
        <el-table-column prop="cp_lx" label="产品类型">
          <template #default="{ row }">
            {{ getDictionaryName(row.cp_lx) }}
          </template>
        </el-table-column>
        <el-table-column prop="bom_code" label="BOM编码" width="180"></el-table-column>
        <el-table-column prop="bom_name" label="BOM名称"></el-table-column>
        <el-table-column prop="bom_bb" label="BOM版本"></el-table-column>
        <el-table-column prop="gy_mr" label="默认">
          <template #default="{ row }">
            <el-switch :model-value="row.gy_mr === 1"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="gy_state" label="启用">
          <template #default="{ row }">
            <el-switch :model-value="row.gy_state === 1"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button type="text" @click="Setuproutes(row)">配置路线</el-button>
            <el-button type="text" @click="deleteRow(row)">路线信息</el-button>
            <el-button type="text" @click="editRow(row)">复制</el-button>
            <el-button type="text" @click="editRow(row)">编辑</el-button>
            <el-button type="text" @click="deleteRow(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalItems" layout="total, prev, pager, next, jumper">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { ref, computed, watchEffect } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';


// 封装请求函数
const request = async (url) => {
  try {
    const response = await axios.get(url);
    return response.data;
  } catch (error) {
    console.error(`请求 ${url} 失败:`, error);
    ElMessage.error(`请求失败: ${error.message}`);
    throw error;
  }
};

export default {
  setup() {
    const router = useRouter();
    // 定义响应式数据
    const searchKey = ref('');
    const treeData = ref([]);
    const defaultProps = {
      children: 'children',
      label: 'label',
    };
    const tableData = ref([]);
    const dictionaryNames = ref({});
    const selectedFilter = ref('');
    const searchTable = ref('');
    const currentPage = ref(1);
    const pageSize = ref(2);
    const totalItems = ref(0);

    // 获取表格数据
    const fetchData = async () => {
      const res = await request('/api/Mbd_GY/GetMbd_GY');
      tableData.value = res;
      totalItems.value = res.length;

    };

    // 过滤数据
    const filterData = () => {
      let data = tableData.value;

      // 根据状态筛选
      if (selectedFilter.value) {
        data = data.filter(item => item.gy_state === selectedFilter.value);
      }

      // 根据关键字搜索
      if (searchTable.value) {
        data = data.filter(item =>
          item.gy_code.includes(searchTable.value) ||
          item.gy_name.includes(searchTable.value)
        );
      }

      return data;
    };

    // 计算过滤后的表格数据
    const filteredTableData = computed(() => {
      const filteredData = filterData();
      totalItems.value = filteredData.length;
      const start = (currentPage.value - 1) * pageSize.value;
      return filteredData.slice(start, start + pageSize.value);
    });

    // 新增操作
    const add = () => {
      // 添加逻辑
    };

    // 编辑操作
    const edit = () => {
      // 编辑逻辑
    };

    // 导入操作
    const importData = () => {
      // 导入逻辑
    };

    // 查询操作
    const query = () => {
      console.log('Querying with:', searchTable.value);
    };

    // 重置操作
    const reset = () => {
      selectedFilter.value = '';
      searchTable.value = '';
      currentPage.value = 1;
    };

    // 编辑行操作
    const editRow = (row) => {
      console.log('Editing row:', row);
    };
    const Setuproutes = (row) => {
      router.push({ path: '/ConfigureProcessRoute', query: { gy_code: row.gy_code } });
    }
    // 删除行操作
    const deleteRow = (row) => {
      console.log('Deleting row:', row);
    };

    // 分页切换操作
    const handleCurrentChange = (page) => {
      currentPage.value = page;
    };

    // 获取字典名称
    const getDictionaryName = (dictionaryId) => {
      if (!dictionaryId) return '';
      if (dictionaryNames.value[dictionaryId]) {
        return dictionaryNames.value[dictionaryId];
      }
      // 发起异步请求获取字典名称
      formatDictionaryName(dictionaryId);
      return '加载中...';
    };

    // 格式化字典名称
    const formatDictionaryName = async (dictionaryId) => {
      try {
        const data = await request(`/api/Dict/GetName?dictionary_id=${dictionaryId}`);
        dictionaryNames.value[dictionaryId] = data;
      } catch (error) {
        console.error(`Error fetching dictionary name: ${error.message}`);
      }
    };

    // 监听表格数据变化，更新字典名称
    watchEffect(() => {
      const fields = ['gy_fl', 'cp_fl', 'cp_lx'];
      filteredTableData.value.forEach((row) => {
        fields.forEach((field) => {
          if (row[field]) {
            formatDictionaryName(row[field]);
          }
        });
      });
    });

    // 初始化获取数据
    fetchData();

    return {
      searchKey,
      treeData,
      defaultProps,
      tableData,
      selectedFilter,
      searchTable,
      currentPage,
      pageSize,
      totalItems,
      add,
      edit,
      importData,
      query,
      reset,
      editRow,
      deleteRow,
      handleCurrentChange,
      getDictionaryName,
      dictionaryNames,
      filteredTableData,
      Setuproutes,
      router
    };
  },
};
</script>

<style>
.container {
  display: flex;
  gap: 20px;
  height: 95%;
}

.sidebar {
  height: 100%;
}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.eltable {
  height: 95%;
}

.letree {
  height: 100%;
}
</style>